package com.ryan.dispatcher.comp.nested;

import com.ryan.ohos.extension.nested.component.NestedScrollView;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.app.Context;
import ohos.multimodalinput.event.TouchEvent;

public class NestedParentView extends NestedScrollView {

    private int distance;
    private int consumedDistance;
    private ComponentContainer child;

    public NestedParentView(Context context) {
        this(context, null);
    }

    public NestedParentView(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public NestedParentView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
    }

    @Override
    public ComponentContainer getContainer() {
        return this;
    }

    @Override
    public boolean onInterceptTouchEvent(TouchEvent ev) {
        return false;
    }

    @Override
    public void onNestedPreScroll(Component target, int dx, int dy, int[] consumed, int type) {
        calculateDistance();
        if (child.getComponentAt(1).getScrollValue(AXIS_Y) != 0) return;

        int consumedY = 0;
        if (dy >= 0) {
            if (consumedDistance < distance) {
                if (consumedDistance + dy > distance) {
                    consumedY = distance - consumedDistance;
                } else {
                    consumedY = dy;
                }
            }
        } else {
            if (consumedDistance >= 0) {
                if (consumedDistance + dy < 0) {
                    consumedY = -consumedDistance;
                } else {
                    consumedY = dy;
                }
            }
        }

        consumedDistance += consumedY;
        consumed[1] = consumedY;

        child.getComponentAt(0).setTranslationY(consumedDistance >> 1);

        scrollBy(0, consumedY);
    }

    @Override
    public void onNestedScroll(Component target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type, int[] consumed) {
        super.onNestedScroll(target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type, consumed);
    }

    @Override
    public boolean onNestedPreFling(Component target, float velocityX, float velocityY) {
        return super.onNestedPreFling(target, velocityX, velocityY);
    }

    private void calculateDistance() {
        if (distance <= 0) {
            child = (ComponentContainer) getComponentAt(0);
            distance = child.getComponentAt(0).getHeight();
        }
    }
}
